<!DOCTYPE html>
<html lang=>
    <head>
        <meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta http-equiv="cache-control" content="no-cache" />
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<meta name="format-detection" content="telephone=no" />
<meta name="author" content='yi_Xu' />
<meta name="description" content='Python 中有好用的 logging 模块，方便我们为程序添加 log 输出，我一直希望能够写个小程序，现在的现在有个小的关于数据提取的小程序，我希望能够提取相关数据，但是用 print 的方式来观察输出实在是忧伤，所以我试着配置了 log ，问题出现了，我希望同时输出到控制台和文件中保存，恩，怎么配置呢?' />
<meta name="keywords" content='web,python,blog,batch' />
<meta name="generator" content="Hugo 0.80.0" />
<meta property="og:url" content='https://www.yixuju.cn/programming/python/python3-logconfig/' />
<meta property="og:title" content='Python3 中的 log 文件配置方法' />
<meta property="og:description" content='Python 中有好用的 logging 模块，方便我们为程序添加 log 输出，我一直希望能够写个小程序，现在的现在有个小的关于数据提取的小程序，我希望能够提取相关数据，但是用 print 的方式来观察输出实在是忧伤，所以我试着配置了 log ，问题出现了，我希望同时输出到控制台和文件中保存，恩，怎么配置呢?' />
<meta property="og:site_name" content='逸絮居' />
<meta property="og:image" content='https://www.yixuju.cn/img/background.jpg' />
<meta property="og:locale" content='zh-CN' />
<meta property="fb:app_id" content='198934840692875' />
<meta property="fb:admins" content='' />
<meta itemprop="name" content='Python3 中的 log 文件配置方法' />
<meta itemprop="description" content='Python 中有好用的 logging 模块，方便我们为程序添加 log 输出，我一直希望能够写个小程序，现在的现在有个小的关于数据提取的小程序，我希望能够提取相关数据，但是用 print 的方式来观察输出实在是忧伤，所以我试着配置了 log ，问题出现了，我希望同时输出到控制台和文件中保存，恩，怎么配置呢?' />
<meta itemprop="image" content='https://www.yixuju.cn/img/background.jpg' />
<meta name="twitter:card" content='summary' />

<meta name="twitter:site" content='' />

<meta name="twitter:creator" content='' />
<meta name="twitter:title" content='Python3 中的 log 文件配置方法' />
<meta name="twitter:description" content='Python 中有好用的 logging 模块，方便我们为程序添加 log 输出，我一直希望能够写个小程序，现在的现在有个小的关于数据提取的小程序，我希望能够提取相关数据，但是用 print 的方式来观察输出实在是忧伤，所以我试着配置了 log ，问题出现了，我希望同时输出到控制台和文件中保存，恩，怎么配置呢?' />
<meta name="twitter:image" content='https://www.yixuju.cn/img/background.jpg' />
<title>Python3 中的 log 文件配置方法 | 逸絮居 </title>
<link rel="canonical" href=https://www.yixuju.cn/programming/python/python3-logconfig/ />
<link rel="icon" type="image/x-icon" href=/favicon.ico />
<link rel="icon" type="image/png" href=/favicon.png />
<link rel="alternate" type="application/rss+xml" title="RSS" href="/index.xml" />
<link rel="stylesheet" href=/css/style.min.css />
<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/clipboard@2/dist/clipboard.min.js"></script>
<script src=/js/custom.min.js></script>
        
        
    </head>
    <body>
        <div>
    <a href=/about>
        <img id="mobile-avatar" class="mobile animated zoomIn" src=/img/avatar.jpg alt=yi_Xu>
    </a>
</div>
<div id="mobile-navbar" class="mobile">
    <div class=" button mobile-navbar">
        <span>菜单</span>
    </div>
</div>
<div id="gotop" class="mobile gotop">
    <div class=" button mobile-navbar">
        <span>置顶</span>
    </div>
</div>
<div id="jquery-menu" class="mobile">
    <ul id="mobile-menu">
        
            
                <li>
                    <a href= />
                        首页
                    </a>
                </li>
            
        
            
                
                    <li>
                        <a href=/programming/>编程体验</a>
                    </li>
                
                    <li>
                        <a href=/other/>其他分享</a>
                    </li>
                
                    <li>
                        <a href=/blog/>生活感悟</a>
                    </li>
                
            
        
            
                <li>
                    <a href= /page/about/>
                        关于
                    </a>
                </li>
            
        
            
                <li>
                    <a href= /page/cards/>
                        卡片集
                    </a>
                </li>
            
        
    
    <li id="mobile-toc-title">目录<i id="down-up" class="icon-double-angle-down"></i>
    <div id="mobile-toc" class="mobile"><nav id="TableOfContents">
  <ul>
    <li><a href="#问题描述">问题描述</a></li>
    <li><a href="#问题背景">问题背景</a></li>
    <li><a href="#配置文件">配置文件</a>
      <ul>
        <li><a href="#mainpy-文件中导入配置文件"><code>main.py</code> 文件中导入配置文件</a></li>
      </ul>
    </li>
    <li><a href="#模块引入配置">模块引入配置</a></li>
    <li><a href="#解决模块引入配置的问题">解决模块引入配置的问题</a></li>
    <li><a href="#其他补充">其他补充</a></li>
  </ul>
</nav></div></li>

</div>
        <header>
    <div id="header">
        <a id = "site-title" href= https://www.yixuju.cn >
            <span>逸絮居</span>
        </a>
        <ul id="header-menu">
            <li>
                <a class="gotop" href="#">置顶</a>
            </li>
            
            
                <li>
                    <a href= / >
                        首页
                    </a>
                </li>
            
                <li>
                    <a href= /page/archieves/ >
                        归档
                    </a>
                </li>
            
                <li>
                    <a href= /page/about/ >
                        关于
                    </a>
                </li>
            
                <li>
                    <a href= /page/cards/ >
                        卡片集
                    </a>
                </li>
            
        </ul>
    </div>
</header>

        <div id="container">
            <section id="main">
                
    <article id="post" class="card">
    <div id="post-title">
        <h1>Python3 中的 log 文件配置方法</h1>
    </div>
    <div id="post-cotent">
        <p><code>Python</code> 中有好用的 <code>logging</code> 模块，方便我们为程序添加 <code>log</code> 输出，我一直希望能够写个小程序，现在的现在有个小的关于数据提取的小程序，我希望能够提取相关数据，但是用 <code>print</code> 的方式来观察输出实在是忧伤，所以我试着配置了 <code>log</code> ，问题出现了，我希望同时输出到控制台和文件中保存，恩，怎么配置呢?</p>
<h2 id="问题描述">问题描述</h2>
<p>根据 <code>logconfig.yaml</code> 文件，配置 <code>log</code>，测试模块文件。</p>
<h2 id="问题背景">问题背景</h2>
<blockquote>
<p>此处引用输出级别描述：</p>
<p>作者：好吃的野菜</p>
<p>链接：<a href="http://www.jianshu.com/p/feb86c06c4f4">http://www.jianshu.com/p/feb86c06c4f4</a></p>
<p>來源：简书</p>
<p>著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。</p>
</blockquote>
<table>
<thead>
<tr>
<th style="text-align:center">输出级别</th>
<th style="text-align:center">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">级别</td>
<td style="text-align:center">何时使用</td>
</tr>
<tr>
<td style="text-align:center">DEBUG</td>
<td style="text-align:center">详细信息，典型地调试问题时会感兴趣。</td>
</tr>
<tr>
<td style="text-align:center">INFO</td>
<td style="text-align:center">证明事情按预期工作。</td>
</tr>
<tr>
<td style="text-align:center">WARNING</td>
<td style="text-align:center">表明发生了一些意外，或者不久的将来会发生问题（如‘磁盘满了’）。软件还是在正常工作。</td>
</tr>
<tr>
<td style="text-align:center">ERROR</td>
<td style="text-align:center">由于更严重的问题，软件已不能执行一些功能了。</td>
</tr>
<tr>
<td style="text-align:center">CRITICAL</td>
<td style="text-align:center">严重错误，表明软件已不能继续运行了。</td>
</tr>
</tbody>
</table>
<p>从上往下，信息级别依次升高！</p>
<p>可采用的 <code>format</code> 格式关键词：</p>
<table>
<thead>
<tr>
<th style="text-align:center">关键词</th>
<th style="text-align:center">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">%(levelno)s</td>
<td style="text-align:center">打印日志级别的数值</td>
</tr>
<tr>
<td style="text-align:center">%(levelname)s</td>
<td style="text-align:center">打印日志级别名称</td>
</tr>
<tr>
<td style="text-align:center">%(pathname)s</td>
<td style="text-align:center">打印当前执行程序的路径</td>
</tr>
<tr>
<td style="text-align:center">%(filename)s</td>
<td style="text-align:center">打印当前执行程序名称</td>
</tr>
<tr>
<td style="text-align:center">%(funcName)s</td>
<td style="text-align:center">打印日志的当前函数</td>
</tr>
<tr>
<td style="text-align:center">%(lineno)d</td>
<td style="text-align:center">打印日志的当前行号</td>
</tr>
<tr>
<td style="text-align:center">%(asctime)s</td>
<td style="text-align:center">打印日志的时间</td>
</tr>
<tr>
<td style="text-align:center">%(thread)d</td>
<td style="text-align:center">打印线程 id</td>
</tr>
<tr>
<td style="text-align:center">%(threadName)s</td>
<td style="text-align:center">打印线程名称</td>
</tr>
<tr>
<td style="text-align:center">%(process)d</td>
<td style="text-align:center">打印进程 ID</td>
</tr>
<tr>
<td style="text-align:center">%(message)s</td>
<td style="text-align:center">打印日志信息</td>
</tr>
</tbody>
</table>
<h2 id="配置文件">配置文件</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-yaml" data-lang="yaml"><span class="nt">version</span><span class="p">:</span><span class="w"> </span><span class="m">1</span><span class="w">
</span></code></pre></td></tr></table>
</div>
</div><p><code>version</code> 键值为 <code>1</code> ，表示启用这个配置。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-yaml" data-lang="yaml"><span class="nt">formatters</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">simple</span><span class="p">:</span><span class="w">
</span><span class="w">    </span><span class="nt">format</span><span class="p">:</span><span class="w"> </span><span class="s1">&#39;%(asctime)s - %(filename)s - %(lineno)d - [%(levelname)s] %(message)s&#39;</span><span class="w">
</span></code></pre></td></tr></table>
</div>
</div><p><code>formatters</code> 键值中需要有对应的 <code>format</code> 设置，可自定义 <code>format</code> 。
<code>datefmt</code> 格式采用 <code>time.strftime</code> 标准模式，此处不设置，自动启用默认。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-yaml" data-lang="yaml"><span class="nt">handlers</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">console</span><span class="p">:</span><span class="w">
</span><span class="w">    </span><span class="nt">class</span><span class="p">:</span><span class="w"> </span><span class="l">logging.StreamHandler</span><span class="w">
</span><span class="w">    </span><span class="nt">level</span><span class="p">:</span><span class="w"> </span><span class="l">WARNING</span><span class="w">
</span><span class="w">    </span><span class="nt">formatter</span><span class="p">:</span><span class="w"> </span><span class="l">simple</span><span class="w">
</span><span class="w">    </span><span class="nt">stream</span><span class="p">:</span><span class="w"> </span><span class="l">ext://sys.stdout</span><span class="w">
</span><span class="w">  </span><span class="nt">logfile</span><span class="p">:</span><span class="w">
</span><span class="w">    </span><span class="nt">class</span><span class="p">:</span><span class="w"> </span><span class="l">logging.handlers.RotatingFileHandler</span><span class="w">
</span><span class="w">    </span><span class="nt">level</span><span class="p">:</span><span class="w"> </span><span class="l">DEBUG</span><span class="w">
</span><span class="w">    </span><span class="nt">formatter</span><span class="p">:</span><span class="w"> </span><span class="l">simple</span><span class="w">
</span><span class="w">    </span><span class="nt">filename</span><span class="p">:</span><span class="w"> </span><span class="l">log.log</span><span class="w">
</span><span class="w">    </span><span class="nt">maxBytes</span><span class="p">:</span><span class="w"> </span><span class="m">10485760</span><span class="w">
</span><span class="w">    </span><span class="nt">backupCount</span><span class="p">:</span><span class="w"> </span><span class="m">3</span><span class="w">
</span></code></pre></td></tr></table>
</div>
</div><p><code>Handlers</code> 是处理 <code>log</code> 的处理器，主要配置输出模式，这里我设置两种模式，控制台（ <code>console</code> ）和日志文件（ <code>logfile</code> ）。</p>
<p><code>class</code> 设定 log 采用的输出模式，不同的 <code>class</code> 有着不同的参数， <code>lever</code> 指定处理器处理的最小级别。</p>
<ul>
<li>
<p><code>StreamHandler</code> 是流输出模式，此处特殊设置流的去处 <code>stream</code> 为 <code>ext：//sys.stdout</code> , <code>sys.stdout</code> 是控制台输出位，加上 <code>ext：//</code> 是为了让 <code>Yaml</code> 识别。</p>
</li>
<li>
<p><code>RotatingFileHandler</code> 是循环文件模式，此处特殊设置 <code>filename</code> 、 <code>maxBytes</code> 、 <code>backupCount</code> 的参数。其中 <code>filename</code> 指定保存文件的名称， <code>maxBytes</code> 指定文件大小的最大值， <code>backupCount</code> 指定文件保存数目的最大值，以序号标注，如果超过次数目，默认删掉最早的，更新文件名。</p>
</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-yaml" data-lang="yaml"><span class="nt">loggers</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">logger</span><span class="p">:</span><span class="w">
</span><span class="w">    </span><span class="nt">level</span><span class="p">:</span><span class="w"> </span><span class="l">INFO</span><span class="w">
</span><span class="w">    </span><span class="nt">handlers</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="l">logfile]</span><span class="w">
</span><span class="w">    </span><span class="nt">propagate</span><span class="p">:</span><span class="w"> </span><span class="kc">yes</span><span class="w">
</span><span class="w"></span><span class="nt">root</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">level</span><span class="p">:</span><span class="w"> </span><span class="l">WARNING</span><span class="w">
</span><span class="w">  </span><span class="nt">handlers</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="l">console]</span><span class="w">
</span></code></pre></td></tr></table>
</div>
</div><p><code>loggers</code> 指定自定义的 <code>log</code> 名称，此处设置名称为 <code>logger</code> ，<code>propagate</code> 指定是否将信息传到其他 <code>loggers</code> ，这里设置为 <code>yes</code> ，这样 logger 接收到的错误信息可以传到 <code>root</code> 那里， 以供显示输出。</p>
<p>完整配置文件（ <code>logconfig.yaml</code> ）如下</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-yaml" data-lang="yaml"><span class="nt">version</span><span class="p">:</span><span class="w"> </span><span class="m">1</span><span class="w">
</span><span class="w"></span><span class="nt">formatters</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">simple</span><span class="p">:</span><span class="w">
</span><span class="w">    </span><span class="nt">format</span><span class="p">:</span><span class="w"> </span><span class="s1">&#39;%(asctime)s - %(filename)s - %(lineno)d - [%(levelname)s] %(message)s&#39;</span><span class="w">
</span><span class="w"></span><span class="nt">handlers</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">console</span><span class="p">:</span><span class="w">
</span><span class="w">    </span><span class="nt">class</span><span class="p">:</span><span class="w"> </span><span class="l">logging.StreamHandler</span><span class="w">
</span><span class="w">    </span><span class="nt">level</span><span class="p">:</span><span class="w"> </span><span class="l">WARNING</span><span class="w">
</span><span class="w">    </span><span class="nt">formatter</span><span class="p">:</span><span class="w"> </span><span class="l">simple</span><span class="w">
</span><span class="w">    </span><span class="nt">stream</span><span class="p">:</span><span class="w"> </span><span class="l">ext://sys.stdout</span><span class="w">
</span><span class="w">  </span><span class="nt">logfile</span><span class="p">:</span><span class="w">
</span><span class="w">    </span><span class="nt">class</span><span class="p">:</span><span class="w"> </span><span class="l">logging.handlers.RotatingFileHandler</span><span class="w">
</span><span class="w">    </span><span class="nt">level</span><span class="p">:</span><span class="w"> </span><span class="l">DEBUG</span><span class="w">
</span><span class="w">    </span><span class="nt">formatter</span><span class="p">:</span><span class="w"> </span><span class="l">simple</span><span class="w">
</span><span class="w">    </span><span class="nt">filename</span><span class="p">:</span><span class="w"> </span><span class="l">log.log</span><span class="w">
</span><span class="w">    </span><span class="nt">maxBytes</span><span class="p">:</span><span class="w"> </span><span class="m">10485760</span><span class="w">
</span><span class="w">    </span><span class="nt">backupCount</span><span class="p">:</span><span class="w"> </span><span class="m">3</span><span class="w">
</span><span class="w"></span><span class="nt">loggers</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">logger</span><span class="p">:</span><span class="w">
</span><span class="w">    </span><span class="nt">level</span><span class="p">:</span><span class="w"> </span><span class="l">INFO</span><span class="w">
</span><span class="w">    </span><span class="nt">handlers</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="l">logfile]</span><span class="w">
</span><span class="w">    </span><span class="nt">propagate</span><span class="p">:</span><span class="w"> </span><span class="kc">yes</span><span class="w">
</span><span class="w"></span><span class="nt">root</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">level</span><span class="p">:</span><span class="w"> </span><span class="l">WARNING</span><span class="w">
</span><span class="w">  </span><span class="nt">handlers</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="l">console]</span><span class="w">
</span></code></pre></td></tr></table>
</div>
</div><h3 id="mainpy-文件中导入配置文件"><code>main.py</code> 文件中导入配置文件</h3>
<p><code>main.py</code> 中使用函数导入文件</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>
<span class="kn">import</span> <span class="nn">yaml</span>
<span class="k">def</span> <span class="nf">setup_logging</span><span class="p">(</span><span class="n">default_path</span> <span class="o">=</span> <span class="s2">&#34;./logconfig.yaml&#34;</span><span class="p">,</span><span class="n">default_level</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span><span class="n">env_key</span> <span class="o">=</span> <span class="s2">&#34;LOG_CFG&#34;</span><span class="p">):</span>
    <span class="n">path</span> <span class="o">=</span> <span class="n">default_path</span>
    <span class="n">value</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="n">env_key</span><span class="p">,</span><span class="bp">None</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">value</span><span class="p">:</span>
        <span class="n">path</span> <span class="o">=</span> <span class="n">value</span>
    <span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">path</span><span class="p">):</span>
        <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">,</span><span class="s2">&#34;r&#34;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
            <span class="n">config</span> <span class="o">=</span> <span class="n">yaml</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
            <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">dictConfig</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span> <span class="o">=</span> <span class="n">default_level</span><span class="p">)</span>
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">setup_logging</span><span class="p">(</span><span class="n">default_path</span> <span class="o">=</span> <span class="s2">&#34;./logconfig.yaml&#34;</span><span class="p">)</span>
    <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s2">&#34;logger&#34;</span><span class="p">)</span>

<span class="c1">#测试</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">&#34;测试debug&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&#34;测试info&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&#34;测试warn&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s2">&#34;测试error&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s2">&#34;测试critical&#34;</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>控制台输出如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">2017-08-17 20:32:11,723 - main.py - 39 - [WARNING] 测试warn
2017-08-17 20:32:11,724 - main.py - 40 - [ERROR] 测试error
2017-08-17 20:32:11,724 - main.py - 41 - [CRITICAL] 测试critical
</code></pre></td></tr></table>
</div>
</div><p><code>log.log</code> 文件输出如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">2017-08-17 20:32:11,723 - main.py - 38 - [INFO] 测试info
2017-08-17 20:32:11,723 - main.py - 39 - [WARNING] 测试warn
2017-08-17 20:32:11,724 - main.py - 40 - [ERROR] 测试error
2017-08-17 20:32:11,724 - main.py - 41 - [CRITICAL] 测试critical
</code></pre></td></tr></table>
</div>
</div><h2 id="模块引入配置">模块引入配置</h2>
<p>如果模块文件需要引入 <code>log</code> 配置，
如下使用：</p>
<p><code>test.py</code> 内容如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s2">&#34;logger&#34;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">test</span><span class="p">()</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">&#34;测试debug&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&#34;测试info&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&#34;测试warn&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s2">&#34;测试error&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s2">&#34;测试critical&#34;</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p><code>main.py</code> 内容如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="nn">test</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>
<span class="kn">import</span> <span class="nn">yaml</span>
<span class="k">def</span> <span class="nf">setup_logging</span><span class="p">(</span><span class="n">default_path</span> <span class="o">=</span> <span class="s2">&#34;./logconfig.yaml&#34;</span><span class="p">,</span><span class="n">default_level</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span><span class="n">env_key</span> <span class="o">=</span> <span class="s2">&#34;LOG_CFG&#34;</span><span class="p">):</span>
    <span class="n">path</span> <span class="o">=</span> <span class="n">default_path</span>
    <span class="n">value</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="n">env_key</span><span class="p">,</span><span class="bp">None</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">value</span><span class="p">:</span>
        <span class="n">path</span> <span class="o">=</span> <span class="n">value</span>
    <span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">path</span><span class="p">):</span>
        <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">,</span><span class="s2">&#34;r&#34;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
            <span class="n">config</span> <span class="o">=</span> <span class="n">yaml</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
            <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">dictConfig</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span> <span class="o">=</span> <span class="n">default_level</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">setup_logging</span><span class="p">(</span><span class="n">default_path</span> <span class="o">=</span> <span class="s2">&#34;./logconfig.yaml&#34;</span><span class="p">)</span>
    <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s2">&#34;logger&#34;</span><span class="p">)</span>

<span class="c1">#测试</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">&#34;测试debug&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">&#34;测试info&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&#34;测试warn&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s2">&#34;测试error&#34;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s2">&#34;测试critical&#34;</span><span class="p">)</span>
    <span class="n">test</span><span class="o">.</span><span class="n">test</span><span class="p">()</span>
</code></pre></td></tr></table>
</div>
</div><p>控制台输出如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">2017-08-17 20:45:40,586 - main.py - 40 - [WARNING] 测试warn
2017-08-17 20:45:40,586 - main.py - 41 - [ERROR] 测试error
2017-08-17 20:45:40,587 - main.py - 42 - [CRITICAL] 测试critical
2017-08-17 20:45:40,587 - test.py - 17 - [WARNING] 测试warn
2017-08-17 20:45:40,587 - test.py - 18 - [ERROR] 测试error
2017-08-17 20:45:40,587 - test.py - 19 - [CRITICAL] 测试critical
</code></pre></td></tr></table>
</div>
</div><p><code>log.log</code> 输出如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">2017-08-17 20:45:14,225 - main.py - 39 - [INFO] 测试info
2017-08-17 20:45:14,225 - main.py - 40 - [WARNING] 测试warn
2017-08-17 20:45:14,225 - main.py - 41 - [ERROR] 测试error
2017-08-17 20:45:14,225 - main.py - 42 - [CRITICAL] 测试critical
2017-08-17 20:45:40,586 - main.py - 39 - [INFO] 测试info
2017-08-17 20:45:40,586 - main.py - 40 - [WARNING] 测试warn
2017-08-17 20:45:40,586 - main.py - 41 - [ERROR] 测试error
2017-08-17 20:45:40,587 - main.py - 42 - [CRITICAL] 测试critical
2017-08-17 20:45:40,587 - test.py - 16 - [INFO] 测试info
2017-08-17 20:45:40,587 - test.py - 17 - [WARNING] 测试warn
2017-08-17 20:45:40,587 - test.py - 18 - [ERROR] 测试error
2017-08-17 20:45:40,587 - test.py - 19 - [CRITICAL] 测试critical
</code></pre></td></tr></table>
</div>
</div><h2 id="解决模块引入配置的问题">解决模块引入配置的问题</h2>
<p>模块引入 <code>log</code> 后，<code>log.log</code> 的信息有重复。</p>
<p>修复方法：
<code>logconfig.yaml</code> 文件添加一条配置</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-yaml" data-lang="yaml"><span class="nt">disable_existing_loggers</span><span class="p">:</span><span class="w"> </span><span class="kc">False</span><span class="w">
</span></code></pre></td></tr></table>
</div>
</div><p><code>log.log</code> 输出如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">2017-08-17 20:57:32,535 - main.py - 39 - [INFO] 测试info
2017-08-17 20:57:32,535 - main.py - 40 - [WARNING] 测试warn
2017-08-17 20:57:32,536 - main.py - 41 - [ERROR] 测试error
2017-08-17 20:57:32,536 - main.py - 42 - [CRITICAL] 测试critical
2017-08-17 20:57:32,536 - test.py - 16 - [INFO] 测试info
2017-08-17 20:57:32,536 - test.py - 17 - [WARNING] 测试warn
2017-08-17 20:57:32,536 - test.py - 18 - [ERROR] 测试error
2017-08-17 20:57:32,536 - test.py - 19 - [CRITICAL] 测试critical
</code></pre></td></tr></table>
</div>
</div><p>问题解决，控制台输出同上。</p>
<h2 id="其他补充">其他补充</h2>
<ul>
<li>
<p><code>logconfig.yaml</code> 配置文件对大小写敏感。</p>
</li>
<li>
<p><code>logconfig.yaml</code> 配置文件使用缩进确认键值包含关系。</p>
</li>
<li>
<p><code>logconfig.yaml</code> 配置文件中同样的缩进表示同一级别键值。</p>
</li>
<li>
<p><code>logconfig.yaml</code> 配置文件键值冒号后需要一个空格！</p>
</li>
<li>
<p>本文仅提供配置文件的部分参数介绍，需要了解详情，建议参考 <a href="http://python.usyiyi.cn/documents/python_352/library/logging.html#logging-levels"><code>Python 3.5.2</code> 标准库 <code>logging</code> 模块文档（中文）</a> 。</p>
</li>
</ul>
    </div>
    <div id="copyright" class="card">

    <div><span> 文章标题：Python3 中的 log 文件配置方法</span>
    </div>


    <div><span> 文章作者：yi_Xu</span>
    </div>


    <div>文章标签：
      <a href="https://www.yixuju.cntags/python3/">#python3&nbsp</a>
      <a href="https://www.yixuju.cntags/log/">#log&nbsp</a>
      <a href="https://www.yixuju.cntags/yaml/">#yaml&nbsp</a>
    </div>



    <div>创建时间：<time datetime=2017-08-17></time>2017-08-17 | 最新更新于：<time datetime=2017-08-17></time>2017-08-17
    </div>

    <div>原始链接：https://www.yixuju.cn/programming/python/python3-logconfig/<span class="copy-path" title="点击复制文章链接" data-clipboard-demo="" data-clipboard-action="copy" data-clipboard-text='https://www.yixuju.cn/programming/python/python3-logconfig/' aria-label="复制成功！"><i class="icon-copy"></i></span>
    </div>

    <div>许可协议：<a rel="license nofollow" href="http://creativecommons.org/licenses/by-nc/4.0/" target="_blank rel="nofollow">知识共享署名-非商业性使用 4.0 国际许可协议</a>
    </div>

</div>
</article>

    
        <div class=" card pagination">
        
            <a class="button prev-page" href=/programming/python/print-for-python/ title=Python&#32;中的&#32;Print>
                上一页
            </a>
        
            
            <a class="button next-page" href= /programming/python/html-to-csv/ title=python&#32;实现&#32;HTML&#32;的表格转&#32;csv>
                下一页
            </a>
            
        </div>
    


            </section>
            <section id="sidebar">
                
    <aside class="sidebar">
  <div id="avatar" class="card">
      <a href=/page/about>
          <img class="animated zoomIn" id="avatar-img" src=/img/avatar.jpg alt=yi_Xu>
      </a>
      <div id="motto">
          <span>品水如酒，愚醉……</span>
      </div>
  </div>
  <div id="categories" class="card">
      <div class="card-title sidebar-title">文章分类</div>
      
      <li class="category">
          <a href=/programming/>编程体验</a>
          
              
                  <ol class="subcategory">
                      <a href=/programming/batch/>batch</a>
                  </ol>
              
                  <ol class="subcategory">
                      <a href=/programming/python/>python</a>
                  </ol>
              
          
      </li>
      
      <li class="category">
          <a href=/other/>其他分享</a>
          
      </li>
      
      <li class="category">
          <a href=/blog/>生活感悟</a>
          
      </li>
      
  </div>
  <div id="communication" class="card">
    <div class="card-title sidebar-title">联系方式</div>
    
    <li class="communication-list">
      <span>GitHub: <a href="https://github.com/yi-Xu-0100" target="_blank" rel="nofollow">@yi-Xu-0100</a></span>
    </li>
    
    <li class="communication-list">
      <span>TG 频道: <a href="https://t.me/yixuju_notify" target="_blank" rel="nofollow">t.me/yixuju_notify</a></span>
    </li>
    
    <li class="communication-list">
      <span>TG 群组: <a href="https://t.me/yixuju" target="_blank" rel="nofollow">t.me/yixuju</a></span>
    </li>
    
    <li class="communication-list">
      <span>QQ 群组: <a href="https://jq.qq.com/?_wv=1027&amp;k=XKIJXRol" target="_blank" rel="nofollow">495793229</a></span>
    </li>
    
    <li class="communication-list">
      <span>联系邮箱: <a href="mailto:yi_Xu@yixuju.cn" target="_blank" rel="nofollow">yi_Xu@yixuju.cn</a></span>
    </li>
    
    <li class="communication-list">
      <span>微信公众号: <a href="" target="_blank" rel="nofollow">逸絮居</a></span>
    </li>
    
</div>
</aside>
    
    <aside class="sidebar">
        <div id="post-menu" class="card">
            <div class="card-title sidebar-title">目录</div>
            <div id="toc"><nav id="TableOfContents">
  <ul>
    <li><a href="#问题描述">问题描述</a></li>
    <li><a href="#问题背景">问题背景</a></li>
    <li><a href="#配置文件">配置文件</a>
      <ul>
        <li><a href="#mainpy-文件中导入配置文件"><code>main.py</code> 文件中导入配置文件</a></li>
      </ul>
    </li>
    <li><a href="#模块引入配置">模块引入配置</a></li>
    <li><a href="#解决模块引入配置的问题">解决模块引入配置的问题</a></li>
    <li><a href="#其他补充">其他补充</a></li>
  </ul>
</nav></div>
        </div>
    </aside>


            </section>
        </div>
        <footer>
    <a  
            href="mailto:yi_Xu@yixuju.cn"
            target = "_blank"
        
        target = "_self" rel="nofollow">
            &copy; 2014 - 2022 yi_Xu
    </a>
    <i class="icon-lightbulb"></i>
    <a href="https://gohugo.io/" target="_blank" rel="nofollow">Power_by Hugo 0.80.0</a>
    <i class="icon-coffee"></i>
    <a href="https://github.com/yi-Xu-0100/hugo-theme-whiteink" target="_blank">Theme_by WhiteInk</a>
    
        <i class="icon-legal"></i>
        <a href="https://beian.miit.gov.cn/" target="_blank" rel="nofollow">鲁 ICP 备 17049362 号</a>
    
</footer>
    </body>
</html>